package com.hwl.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hwl.server.entity.Menu;
import com.hwl.server.entity.MenuRole;
import com.hwl.server.entity.Role;
import com.hwl.server.pojo.RespBean;
import com.hwl.server.service.MenuRoleService;
import com.hwl.server.service.MenuService;
import com.hwl.server.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 权限组
 */
@Api(tags = "PermissionController")
@RestController
@RequestMapping("/system/basic/permiss")
public class PermissionController {

    @Resource
    private RoleService roleService;
    @Resource
    private MenuService menuService;
    @Resource
    private MenuRoleService menuRoleService;

    @ApiOperation("获取所有角色")
    @GetMapping("/")
    public List<Role> getAllRoles() {
        return roleService.list();
    }

    @ApiOperation("添加角色")
    @PostMapping("/role")
    public RespBean addRole(@RequestBody Role role) {
        if (!role.getName().startsWith("Role_")) {
            role.setName("Role_" + role.getName());
        }
        if (roleService.save(role)) {
            return RespBean.success("添加角色成功！");
        }
        return RespBean.error("添加角色失败！");
    }

    @ApiOperation("删除角色")
    @DeleteMapping("/role/{rid}")
    public RespBean deleteRole(@PathVariable Integer rid) {
        if (roleService.removeById(rid)) {
            return RespBean.success("删除角色成功！");
        }
        return RespBean.error("删除角色失败！");
    }

    @ApiOperation("查询所有菜单")
    @GetMapping("menus")
    public List<Menu> getAllMenus() {
        return menuService.getAllMenus();
    }

    @ApiOperation("根据角色id获取对应的菜单id")
    @GetMapping("mid/{rid}")
    public List<Integer> getMidByRid(@PathVariable Integer rid) {
        return menuRoleService.list(new QueryWrapper<MenuRole>().eq("rid", rid))
                .stream().map(MenuRole::getMid).collect(Collectors.toList());
    }

    @ApiOperation("更新角色菜单")
    @PutMapping("/")
    public RespBean updateMenuRole(Integer rid, Integer[] mids) {
        return menuRoleService.updateMenuRole(rid, mids);
    }
}
